<?php
declare (strict_types = 1);

namespace app\lib;

class Arr {

    // 分类树， 支持无限级
    public static function getTree($data = []) : array {
        if (empty($data)) {
            return [];
        }
        $items = array_combine(array_column($data, "id"), $data);
        $tree = [];
        foreach ($items as $id=>$item){
            if (isset($items[$item["pid"]])) {
                $items[$item["pid"]]["list"][] = &$items[$id];
            }else{
                $tree[] = &$items[$id];
            }
        }

        return $tree;
    }

    // 切割三级数组
    public static function sliceTreeArr($data = [], $firstCount = 5, $secondCount = 4, $thirdCount= 5) : array {
        if (empty($data)) {
            return [];
        }

        $data = array_slice($data, 0, $firstCount);
        foreach ($data as $key => $datum) {
            if (!empty($datum["list"]) && count($datum["list"]) > 0) {
                $data[$key]["list"] = array_slice($datum["list"], 0, $secondCount);
                foreach ($data[$key]["list"] as $_key=>$_datum) {
                    if (!empty($_datum["list"]) && count($_datum["list"]) > 0) {
                        $data[$key][$_key]["list"] = array_slice($_datum, 0, $thirdCount);
                    }
                }
            }
        }

        return $data;
    }

    public static function multiSort($sortField = "updatedTime", $sortArr = [], $sort = SORT_DESC) : array {
        if (empty($sortArr)) {
            return [];
        }
        array_multisort(array_column($sortArr, $sortField), SORT_DESC, $sortArr);

        return $sortArr;
    }
}